import React from "react";
import { Form, Input, Button } from "antd";
import bg from "../../assets/images/bg-login.webp";
import { LoginDataState } from "../../types";
import { login } from "../../api";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const onFinish = async (values: LoginDataState) => {
    const resp = await login(values);
    const { code, data } = resp.data;
    if (code === 200) {
      // 保存数据
      dispatch({ type: "loginSuccess", payload: data });
      // 跳转页面
      // navigate("/");
    }
  };

  return (
    <div className="login" style={{ backgroundImage: `url(${bg})` }}>
      <Form
        className="form"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={() => {}}
      >
        <Form.Item wrapperCol={{ span: 20, offset: 4 }}>
          <h2>用户登录</h2>
        </Form.Item>
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: "用户名不可以为空！！",
            },
            {
              pattern: /^(1[3-9]\d{9})|(\w+@\w+\.(com|cn|net))$/,
              message: "用户名必须是手机号或者邮箱",
            },
          ]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: "密码不可以为空！！",
            },
            {
              pattern: /^[A-Z]/,
              message: "开头必须是大写字母！",
            },
            {
              pattern: /^\w{6,12}$/,
              message: "密码必须6-12未数字、字母、下划线组成",
            },
          ]}
        >
          <Input.Password></Input.Password>
        </Form.Item>
        <Form.Item wrapperCol={{ span: 20, offset: 4 }}>
          <Button block type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
